/**
 * FileFind - ftp/shares indexing and search php engine
 * Module: agent-java
 * Description: Agent written in java language
 * Copyright (c) 2003-2010 Rage Steel, www.gt2.ru
 */
package ru.ffind.agent.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.springframework.jdbc.core.RowMapper;

import static ru.ffind.agent.db.DbTools.getRsByte;
import static ru.ffind.agent.db.DbTools.getRsShort;
import static ru.ffind.agent.db.DbTools.getRsInteger;

/**
 * Host description in database.
 * FIXME Add hostType enum
 * 
 * @author Rage Steel
 */
public class DbHost {
	private Short hostId;
	private Byte hostType;
	private String hostName;
	private Integer lockPid;
	private Date lockDatetime;
	private Integer rootDirId;
	private Date crawlLast; 
	
	public DbHost(Short hostId, Byte hostType, String hostName, Integer lockPid,
			Date lockDatetime, Integer rootDirId, Date crawlLast) {
		super();
		this.hostId = hostId;
		this.hostType = hostType;
		this.hostName = hostName;
		this.lockPid = lockPid;
		this.lockDatetime = lockDatetime;
		this.rootDirId = rootDirId;
		this.crawlLast = crawlLast;
	}

	public final static RowMapper<DbHost> ROW_MAPPER = new RowMapper<DbHost>() {
		
		@Override
		public DbHost mapRow(ResultSet rs, int rowNum) throws SQLException {
	
			return new DbHost(
				getRsShort(rs, "host_id"),
				getRsByte(rs, "host_type"),
				rs.getString("host_name"),
				getRsInteger(rs, "lock_pid"),
				rs.getTimestamp("lock_datetime"),
				getRsInteger(rs, "root_dir_id"),
				rs.getTimestamp("crawl_last")
			);
		}
	};

	
	public boolean isCrawlNeeded() {
		if (null == crawlLast) {
			return true;
		}
		
		Date now = new Date();
		return (Math.abs(now.getTime() - crawlLast.getTime()) > 24 * 60 * 60 * 1000);
	}
	
	// Getters
	
	public Short getHostId() {
		return hostId;
	}

	public Byte getHostType() {
		return hostType;
	}

	public String getHostName() {
		return hostName;
	}

	public Integer getLockPid() {
		return lockPid;
	}

	public Date getLockDatetime() {
		return lockDatetime;
	}

	public Integer getRootDirId() {
		return rootDirId;
	}
	
	public Date getCrawlLast() {
		return crawlLast;
	}
	
	// Setters
	
	public void setHostType(Byte hostType) {
		this.hostType = hostType;
	}

	public void setHostName(String hostName) {
		this.hostName = hostName;
	}

	public void setLockPid(Integer lockPid) {
		this.lockPid = lockPid;
	}

	public void setLockDatetime(Date lockDatetime) {
		this.lockDatetime = lockDatetime;
	}

	public void setRootDirId(Integer rootDirId) {
		this.rootDirId = rootDirId;
	}

	public void setCrawlLast(Date crawlLast) {
		this.crawlLast = crawlLast;
	}
}
